import java.util.Scanner;

public class BinarySearchTest {
    /**
     * 二分搜索
     * @param args
     */
    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        System.out.println("请输入需要排序的数组长度：");
        int n=in.nextInt();
        int[] nums = new int[n];
        System.out.print("请依次输入数组元素：");
        for(int i=0;i<n;i++){
            nums[i]=in.nextInt();
        }
        System.out.print("请输入目标元素的值：");
        int target = in.nextInt();
        int index = binarySearch(nums, target);
        if (index == -1) {
            System.out.println("目标元素不存在于数组中");
        } else {
            System.out.println("目标元素在数组中的位置为：" + index);
        }
    }


    public static int binarySearch(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }



}
